package leetcode;

import java.util.HashMap;
import java.util.Map;

public class TwoSum {

    public static int[] nums = {3, 2, 4};

    public static void main(String[] args) {
        int[] result = twoSum(6, nums);
        if (result != null) {
            for (int i = 0; i < result.length; i++) {
                System.out.println(result[i]);
            }
        }
    }

    public static void simple(int target, int[] source) {
        for (int i = 0; i < source.length - 1; i++) {
            for (int j = i + 1; j < source.length; j++) {
                if ((source[i] + source[j]) == target) {
                    System.out.println(source[i] + " + " + source[j] + " = " + target);
                }
            }
        }
    }

    public static int[] twoSum(int target, int[] source) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < source.length; i++) {
            int value = source[i];
            if (map.containsKey(target - value)) {
                return new int[]{map.get(target - value), i};
            } else {
                map.put(value, i);
            }
        }
        return null;
    }
}
